package cn.edu.cug.cs.gtl.store.sys;

import cn.edu.cug.cs.gtl.common.Pair;
import cn.edu.cug.cs.gtl.protos.*;
import cn.edu.cug.cs.gtl.sql.druid.DruidWrapper;
import cn.edu.cug.cs.gtl.sql.executor.SQLExecutor;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class MenuStore {

    public static Tuples getMenu(TableKey menuTableKey, int menuID) throws Exception{
        Parameters ps = Parameters.newBuilder()
                .addParameter(Parameter.newBuilder().setName("menu_id").setValue(String.valueOf(menuID)).build())
                .build();
        return  SQLExecutor.select(menuTableKey,ps);
    }

    /**
     * 获取指定菜单的子菜单项
     * @param menuID
     * @param userID
     * @return 返回的Tuples中的每个元组有两个值，一个是菜单ID，另一个是菜单名称
     * @throws Exception
     */
    public static Tuples getSubmenus(TableKey menuTableKey, int menuID, int userID) throws Exception{
        String sql = "SELECT\n" +
                "\tt.menu_id,\n" +
                "\tt.menu_name \n" +
                "FROM\n" +
                "\t(\n" +
                "\tSELECT\n" +
                "\t\tmenu_id,\n" +
                "\t\tparent_id,\n" +
                "\t\torder_num,\n" +
                "\t\tmenu_name \n" +
                "\tFROM\n" +
                "\t\tsys_menu \n" +
                "\tWHERE\n" +
                "\t\tmenu_id IN (\n" +
                "\t\tSELECT\n" +
                "\t\t\tmenu_id \n" +
                "\t\tFROM\n" +
                "\t\t\tsys_role_menu \n" +
                "\t\tWHERE\n" +
                "\t\trole_id IN ( SELECT role_id FROM sys_user_role WHERE user_id = ? ))) t \n" +
                "WHERE\n" +
                "\tt.parent_id = ? \n" +
                "ORDER BY\n" +
                "\tt.order_num";

        Connection connection = DruidWrapper.getConnection(menuTableKey);
        Pair<String,Object[]> p = new Pair<>();
        p.setKey(sql);
        Object[] objects = new Object[2];
        objects[0] = Long.valueOf(userID);
        objects[1] = Long.valueOf(menuID);
        p.setValue(objects);
        Tuples tuples = SQLExecutor.executeQuery(connection,p);
        connection.close();
        return tuples;
    }

    public static List<Pair<Long,String>> getSubmenuList(TableKey menuTableKey, int menuID, int userID) throws Exception{
        Tuples tuples = getSubmenus(menuTableKey,menuID,userID);
        List<Pair<Long,String>> list = new ArrayList<>();
        for(Tuple t: tuples.getTupleList()){
            list.add(new Pair<>(Long.valueOf(t.getValue(0)),t.getValue(1)));
        }
        return list;
    }
    public static TableInfo getTableInfo(TableKey key) throws Exception{
        return SQLExecutor.getTableInfo(key);
    }
}
